<template>
  <!-- start 产品模板列表 -->
  <div
    class="product-template-list-view customer-contact-list-view"
    :class="customerContactListClassNames"
    ref="productTemplateListPage"
    v-loading.fullscreen.lock="loadingListData"
  >
    <!-- start 搜索 -->
    <div ref="tableHeaderContainer"  class="product-template-list-search-group">
      <!-- start  搜索header -->
      <form class="base-search" onsubmit="return false;">
        <div class="product-template-list-base-search-group input-with-append-search">
          <el-input v-model="searchModel.keyword" :placeholder="$t('common.placeholder.customerContactSearch')" v-trim:blur class="mar-r-12">
            <i slot="prefix" class="el-input__icon el-icon-search"></i>
            <el-button type="primary" slot="append" native-type="submit" @click="searchModel.pageNum=1;search();trackEventHandler('search')" v-track="$track.formatParams('KEYWORD_SEARCH')">{{$t('common.base.search')}}</el-button>
          </el-input>
          <el-button type="plain-third" @click="resetParams" v-track="$track.formatParams('RESET_SEARCH')">{{$t('common.base.reset')}}</el-button>
        </div>
        <span class="advanced-search-visible-btn" @click.self.stop="panelSearchAdvancedToggle">
          <i class="iconfont icon-filter"></i>
          {{$t('component.advancedSearch.title')}}
        </span>
      </form>
      <!-- end 搜索 header -->

      <!-- start 高级搜索表单 -->
      <product-template-search-panel
        :config="{
          fields: this.productFields,
        }"
        ref="searchPanel"
      >
        <div class="advanced-search-btn-group" slot="footer">
          <el-button type="plain-third" @click="resetParams">{{$t('common.base.reset')}}</el-button>
          <el-button type="primary" @click="powerfulSearch" native-type="submit">{{$t('common.base.search')}}</el-button>
        </div>
      </product-template-search-panel>
      <!-- end 高级搜索表单 -->
    </div>
    <!-- end 搜索 -->

    <!-- start content -->
    <div class="product-template-list-content">
      <!--operation bar start-->
      <div ref="tableDoContainer" class="operation-bar-container">
        <div class="top-btn-group"></div>
        <!-- end operation bar-->

        <!-- start 操作按钮组 -->
        <div class="action-button-group">
          <biz-list-checkbox-select v-if="isQywx" :title="$t('common.base.associatedWeChat')" :is-signle="true" :list="customerRelationWxStatusList" @change="onCustonerRelationWxStatusChangedHandler" />
          <el-dropdown trigger="click" v-if="authExport && isButtonDisplayed">
            <span class="el-dropdown-link cur-point" @click="trackEventHandler('moreAction')">
              {{$t('common.base.moreOperator')}}
              <i class="iconfont icon-fdn-select"></i>
            </span>
            <el-dropdown-menu slot="dropdown">
              
              <el-dropdown-item  v-if="isButtonDisplayed">
                <div @click="exportProduct(false)" v-track="$track.formatParams('EXPORT', null, 'MORE_ACTIONS')">{{$t('common.base.export')}}</div>
              </el-dropdown-item>
              
              <el-dropdown-item  v-if="isButtonDisplayed">
                <div @click="exportProduct(true)" v-track="$track.formatParams('EXPORT_ALL', null, 'MORE_ACTIONS')">{{$t('common.base.exportAll')}}</div>
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          <span class="el-dropdown-link cur-point mar-l-12 common-column" @click="showAdvancedSetting" v-track="$track.formatParams('SELECT_COLUMN')">
            {{$t('common.base.choiceCol')}}
            <i class="iconfont icon-fdn-select"></i>
          </span>
        </div>
        <!-- end 操作按钮组 -->
      </div>
      <!-- end  -->

      <!-- <div ref="BaseSelectionBarComponent" class="base-selection-wrapper">
        <base-selection-bar
          ref="baseSelectionBar"
          v-model="multipleSelection"
          @toggle-selection="selectionToggle"
          @show-panel="() => panelTheMultipleSelectionShow = true"
        />
      </div> -->

      <!-- start 表格 -->
      <div class="pad-l-16 pad-r-16 bg-w">
      <el-table
        v-table-style
        :data="page.list"
        :row-key="getRowKey"
        stripe
        border
        class="bbx-normal-list-box"
        @sort-change="sortChange"
        @select="selectionHandle"
        @select-all="selectionHandle"
        @header-dragend="headerDragend"
        :highlight-current-row="false"
        header-row-class-name="base-table-header-v3"
        ref="productTemplateTable"
        :height="tableContainerHeight"
      >
        <template slot="empty">
          <BaseListForNoData v-show="!loadingListData" :notice-msg="$t('common.base.tip.noData')"></BaseListForNoData>
        </template>
        <el-table-column type="selection" width="48" align="center" class-name="select-column"></el-table-column>
        <el-table-column
          v-for="column in columns"
          v-if="column.show"
          :key="column.field"
          :label="column.label"
          :prop="column.field"
          :width="column.width"
          :min-width="column.minWidth || '120px'"
          :sortable="column.sortable"
          show-overflow-tooltip
          :align="column.align"
          :fixed="column.fixLeft || column.fixed || false"
        >
          <template slot-scope="scope">
            <template v-if="column.conType === 'btnArray'">
              <el-dropdown class="dropdown" v-if="column.btnArr.length > 1">
                <span class="cur-point">
                  {{$t('common.base.more')}}<i class="el-icon-arrow-down el-icon--right"></i>
                </span>
                <el-dropdown-menu slot="dropdown" class="lang-select-dropdown">
                  <el-dropdown-item v-for="(item, index) in column.btnArr" :key="index">
                    <div
                      :style="item.styleType1(scope.row)"
                      @click.stop.prevent="item.click(scope.row, scope.$index)"
                    >{{item.name}}</div>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
              <div v-else>
                <a
                  v-for="(item, index) in column.btnArr"
                  :key="index"
                  :class="`view-detail-btn ${index>0?'mar-l-10':''}`"
                  :style="item.styleType(scope.row)"
                  @click.stop.prevent="item.click(scope.row, scope.$index)"
                >{{item.name}}</a>
              </div>
            </template>
            <!-- 客户联系人示例数据 -->
            <div v-if="column.field === 'name'" :class="{ superscript: scope.row.isGuideData || scope.row.guideData }">
              <span class="customer-contact-name">{{ scope.row[column.field] }}</span>
            </div>
            <template v-else-if="column.conType === 'click'">
              <a
                href
                class="view-detail-btn"
                :class="{ 'view-detail-btn-disabled': !hasViewCustomerAuth(scope.row) || !globalIsHaveCustomerViewDetailAuth }"
                :style="`color:${column.color}`"
                @click.stop.prevent="column.click(scope.row)"
                v-if="!scope.needAuth"
              >{{scope.row[column.field]}}</a>
              <p v-else>{{scope.row[column.field]}}</p>
            </template>
            <!-- <template v-else-if="column.field === 'cusName'">
              <a
                href
                class="view-detail-btn"
                @click.stop.prevent="goCustomerInfo(scope.row.customerId)"
              >{{scope.row[column.field]}}</a>
            </template>-->
            <template
              v-else-if="column.formType === 'select'"
            >{{ scope.row[column.field] | displaySelect }}</template>
            <template
              v-else-if="column.formType === 'user'"
            >{{ scope.row[column.field] && (scope.row[column.field].displayName || scope.row[column.field].name) }}</template>
            <template
              v-else-if="column.formType === 'location'"
            >{{ scope.row.attribute[column.field] && scope.row.attribute[column.field].address}}</template>
            <template v-else-if="column.field === 'registeredSource'">
              <el-tooltip
                class="item"
                effect="dark"
                :content="scope.row.esLinkManWXEntities.length>0?scope.row.esLinkManWXEntities[0].nickName:''"
                placement="right"
                v-if="scope.row.registeredSource===1"
              >
                <i class="iconfont icon-weixin1 color-green font-16"></i>
              </el-tooltip>
              {{ scope.row.registeredSource == 2 ? $t('common.base.onlineService') : (scope.row.registeredSource == 3 ? $t('common.fields.customerRegisteredSource.options.weChatIm') : '') }}
            </template>
            <template
              v-else-if="column.field === 'esProductEntities'"
            >{{ transhForm(scope.row.esProductEntities)}}</template>

            <template
              v-else-if="column.field === 'createUser'"
            >{{ scope.row.createUser && scope.row.createUser.displayName }}</template>
            <template v-else-if="column.field === 'name'">
              <div class="customer-contact-name">
                {{ scope.row.name }}
                <ui-wx-tag v-if="scope.row.hasWechat" />
              </div>
            </template>
            <template
              v-else-if="column.field === 'createTime'"
            >{{ scope.row.createTime | formatDate }}</template>

            <div
              v-else-if="column.formType === 'textarea'"
              v-html="buildTextarea(scope.row.attribute[column.field])"
              @click="openOutsideLink"
            ></div>
            
            <template v-else-if="column.field === 'phone'">
              <span class="align-items-center"> 
                {{ scope.row.phone }}
                <biz-call-icon :value="scope.row.phone" />
              </span>
            </template>

            <template v-else>{{scope.row[column.field]}}</template>
          </template>
        </el-table-column>
      </el-table>
      </div>
      <!-- end 表格 -->

      <!-- start 表格底部 -->
      <div ref="tableFooterContainer" class="table-footer bbx-normal-table-footer">
        <div class="list-info">
          <i18n path="common.base.table.totalCount">
            <span place="count" class="level-padding">{{ page.total || 0 }}</span>
          </i18n>
          <template v-if="multipleSelection&&multipleSelection.length>0">
            <i18n path="common.base.table.selectedNth">
              <span
                place="count"
                class="product-template-selected-count"
                @click="panelTheMultipleSelectionShow = true"
              >{{ multipleSelection.length }}</span>
            </i18n>
            <span class="product-template-selected-count" @click="selectionToggle()">{{$t('common.base.clear')}}</span>
          </template>
        </div>
        <el-pagination
          class="product-template-table-pagination"
          background
          @current-change="jump"
          @size-change="handleSizeChange"
          :page-sizes="defaultTableData.defaultPageSizes"
          :page-size="page.pageSize"
          :current-page="page.pageNum"
          layout="prev, pager, next, sizes, jumper"
          :total="page.total"
        ></el-pagination>
      </div>
      <!-- end 表格底部 -->

      <!-- start 导出 -->
      <base-export
        ref="exportProductTemplatePanel"
        :storage-key="exportStorageKey"
        :columns="exportColumns()"
        :build-params="exportParamsBuild"
        :validate="exportCountCheck"
        method="post"
        :action="customerContactComponentsCustomer"
      />
      <!-- end 导出 -->

      <!-- start 已选择列表 -->
      <base-panel :show.sync="panelTheMultipleSelectionShow" width="420px">
        <h3 slot="title">
          <span>{{$t('customerContact.exportPanel.title')}}({{ multipleSelection.length }})</span>
          <i
            v-if="multipleSelection.length > 0"
            class="iconfont icon-qingkongshanchu product-template-panel-btn"
            @click="selectionToggle()"
            :title="$t('customerContact.exportPanel.clearIconTip')"
            data-placement="right"
            v-tooltip
          ></i>
        </h3>

        <div class="product-template-selected-panel">
          <div class="product-template-selected-tip" v-if="multipleSelection.length <= 0">
            <img :src="noDataImage" />
            <p>{{$t('customerContact.exportPanel.noData')}}</p>
          </div>
          <template v-else>
            <div class="product-template-selected-list">
              <div class="product-template-selected-row product-template-selected-head">
                <span class="product-template-selected-name">{{$t('customerContact.exportPanel.name')}}</span>
                <span class="product-template-selected-sn">{{$t('customerContact.exportPanel.phone')}}</span>
              </div>
              <div
                class="product-template-selected-row"
                v-for="item in multipleSelection"
                :key="item.id"
              >
                <span class="product-template-selected-name">{{ item.name }}</span>
                <span class="product-template-selected-sn">{{ item.phone }}</span>
                <button
                  type="button"
                  class="product-template-selected-delete"
                  @click="selectProductTemplateCancel(item)"
                >
                  <i class="iconfont icon-fe-close"></i>
                </button>
              </div>
            </div>
          </template>
        </div>
      </base-panel>
      <!-- end 已选择列表 -->
    </div>
    <!-- end content -->

    <biz-select-column ref="advanced" mode="customerContact" :sotrage-key="'customerContact_select_colum'" @save="saveColumnStatus"/>


    <!-- 编辑联系人弹窗 -->
  <edit-contact-dialog ref="EditContactDialog" :customer="selectedContact.customer" :original-value="selectedContact"></edit-contact-dialog>
  </div>
  <!-- end 产品模板列表 -->
</template>

<script>
// pageDes 客户联系人
import i18n from '@src/locales';
import _, { isEmpty } from 'lodash';
import { safeNewDate } from '@src/util/time';
import Page from '@model/Page';
import platform from '@src/platform';
import { formatDate } from 'pub-bbx-utils';
import { checkButtonDisplayed } from '@src/util/dom';

import EditContactDialog from '@src/modules/customer/view/operationDialog/EditContactDialog.vue';

import { getContactList } from '@src/api/CustomerContact.js';

import SearchPanel from '../components/SearchPanel.vue';
import AuthUtil from '@src/util/auth';
import dingtalk from '@src/util/dingtalk';
import { isBasicEditionHideProduct } from '@shb-lib/version'
import { isQYWX, openAccurateTab } from '@src/util/platform.ts'
import { getRootWindowInitData } from '@src/util/window'
/* export & import */
import { customerContactComponentsCustomer } from '@src/api/Export';

import { storageSet, storageGet, storageRemove } from '@src/util/storageV2';
import { defaultTableData } from '@src/util/table'

import AuthMixin from '@src/mixins/authMixin'
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'
import StorageKeyEnum from '@model/enum/StorageKeyEnum'


import { formatAddress } from 'pub-bbx-utils';
/* 高级搜索面板 列数 */
const PRODUCT_TEMPLATE_LIST_ADVANCE_SEARCH_COLUMN_NUMBER = 'customer_contact_search_column_number';
/* 高级搜索 搜索数据 */
const STORE_USER_FOR_SEARCH_PRODUCT_TEMPLATE = 'store_user_for_search_product_template';
// 产品模板列表数据
const PRODUCT_TEMPLATE_LIST_DATA = 'product_template_list_data';
// 产品模板列表选择
const PRODUCT_CHECK = 'productCheck';
import { getOssUrl } from '@src/util/assets'
const noDataImage = getOssUrl('/no_data.png')

const link_reg = /((((https?|ftp?):(?:\/\/)?)(?:[-;:&=\+\$]+@)?[A-Za-z0-9.-]+|(?:www.|[-;:&=\+\$]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\?\+=&;:%!\/@.\w_]*)#?(?:[-\+=&;%!\?\/@.\w_]*))?)/g;

let pending = false; // 记录交互pending

/** mixin */
import { VersionControlOtherMixin } from '@src/mixins/versionControlMixin'

export default {
  name: 'customer-conctact-customer',
  mixins: [AuthMixin, VersionControlOtherMixin],
  props: {
    initData: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      defaultTableData,
      noDataImage,
      exportStorageKey: StorageKeyEnum.CustomerContactExport,
      isButtonDisplayed: checkButtonDisplayed(),
      auth: {}, // 权限
      columns: [], // 列
      columnNum: 1, // 高级搜索 列数
      loadingListData: false, // 加载列表数据
      page: new Page(), // page 对象
      productTemplateConfig: {
        productTemplateConfig: {},
        productFields: []
      }, // 产品配置项
      searchModel: {
        keyword: '',
        pageSize: 10,
        pageNum: 1,
        orderDetail: {},
        moreConditions: {}
      },
      selectedContact: {}, // 编辑联系人弹窗参数,
      selectColumnState:'customerContactListData',
      // 表单选择系列组件相关参数
      multipleSelection: [],
      panelTheMultipleSelectionShow: false,
      customerRelationWxStatusList: [{ label: this.$t('common.base.associated'), value: true }, { label: this.$t('common.base.notContact'), value: false }],
      hasWechat: null,
      relationWxListValue: [],
      customerContactComponentsCustomer,
      tableContainerHeight:'440px',
    };
  },
  computed: {
    productFields() {
      let _fields = (
        this.initData.productFields || [
          {
            displayName: i18n.t('common.fields.contact.displayName'),
            fieldName: 'name',
            formType: 'text',
            placeHolder: i18n.t('common.placeholder.inputContactName'),
            isExport: false,
            isSystem: 1,
            orderId: 1
          },
          {
            displayName: i18n.t('common.fields.phone.displayName'),
            fieldName: 'phone',
            formType: 'text',
            placeHolder: i18n.t('common.placeholder.inputPhone'),
            isExport: false,
            isSystem: 1,
            orderId: 2
          },
          {
            displayName: i18n.t('common.fields.customer.displayName'),
            fieldName: 'customerId',
            formType: 'customer',
            placeHolder: i18n.t('common.placeholder.selectCustomer'),
            children: ['product', 'addr'], // 有子搜索组件需要声明子组件的fieldName
            isExport: false,
            isNull: 1,
            isSystem: 1,
            orderId: 3
          },
          {
            displayName: i18n.t('common.fields.relationProduct.displayName'),
            fieldName: 'product',
            formType: 'select',
            isExport: false,
            extendType: 'customerExtend', // 组件的type
            extendData: 'customerId', // 需要依赖的参数名称
            extendDisplayName: i18n.t('common.fields.customer.displayName'), // 需要依赖的参数描述
            searchUrl: '/customer/product/list', // 依赖的参数的获取接口
            searchType: 'POST', // 依赖的参数的获取接口方式
            mainKey: 'customerId', // 依赖的参数的获取接口的主要参数名称
            resShowKey: '',
            resTranslate: obj => {
              return {
                value: obj.name,
                id: obj.id
              };
            },
            placeholder: i18n.t('common.placeholder.inputRelationProduct'),
            isNull: 1,
            isSystem: 1,
            orderId: 3
          },
          {
            displayName: i18n.t('common.fields.relationAddress.displayName'),
            fieldName: 'addr',
            formType: 'select',
            extendType: 'customerExtend',
            extendData: 'customerId',
            searchUrl: '/customer/address/list',
            searchType: 'GET',
            mainKey: 'customerId',
            resShowKey: '',
            resTranslate: obj => {
              return {
                value: formatAddress(obj,''),
                id: obj.id
              };
            },
            extendDisplayName: i18n.t('common.fields.customer.displayName'),
            placeholder: i18n.t('common.placeholder.inputRelationAddress'),
            isNull: 1,
            isSystem: 1,
            orderId: 3
          },
          {
            displayName: i18n.t('common.fields.weChatNickname.displayName'),
            fieldName:'weChatNickname',
            formType: 'text',
            placeHolder: i18n.t('common.placeholder.inputWeChatNickname'),
            field: 'weChatNickname',
            isExport: false,
            isSystem: 1,
            orderId: 3
          },
          {
            displayName: i18n.t('common.fields.weChatId.displayName'),
            fieldName:'weChatId',
            formType: 'text',
            placeHolder: i18n.t('common.placeholder.inputWeChatAccount'),
            field: 'weChatId',
            isExport: false,
            isSystem: 1,
            orderId: 3
          },
          {
            displayName: i18n.t('common.fields.sex.displayName'),
            fieldName: 'sex',
            formType: 'select',
            isExport: false,
            isNull: 1,
            isSystem: 1,
            operator: 'between',
            orderId: 4,
            setting: {
              isMulti: false,
              dataSource: [
                {
                  text: i18n.t('common.fields.sex.options.all'),
                  value: ''
                },
                {
                  text: i18n.t('common.fields.sex.options.man'),
                  value: '男'
                },
                {
                  text: i18n.t('common.fields.sex.options.woman'),
                  value: '女'
                }
              ]
            }
          },
          {
            displayName: i18n.t('common.fields.email.displayName'),
            fieldName: 'email',
            formType: 'email',
            placeHolder: i18n.t('common.placeholder.inputEmail'),
            isExport: false,
            isSystem: 1,
            orderId: 5
          },
          {
            displayName: i18n.t('common.fields.position.displayName'),
            fieldName: 'position',
            formType: 'text',
            placeHolder: i18n.t('common.placeholder.inputPosition'),
            isExport: false,
            isSystem: 1,
            orderId: 6
          },
          {
            displayName: i18n.t('common.fields.dept.displayName'),
            fieldName: 'dept',
            formType: 'text',
            placeHolder: i18n.t('common.placeholder.inputDepartment'),
            isExport: false,
            isSystem: 1,
            orderId: 7
          },
          {
            displayName: i18n.t('common.fields.customerRegisteredSource.displayName'),
            fieldName: 'registeredSource',
            formType: 'select',
            isExport: false,
            isNull: 1,
            isSystem: 1,
            operator: 'between',
            orderId: 10,
            setting: {
              isMulti: false,
              dataSource: [
                {
                  text: i18n.t('common.fields.customerRegisteredSource.options.all'),
                  value: ''
                },
                {
                  text: i18n.t('common.fields.customerRegisteredSource.options.officialAccounts'),
                  value: '1'
                },
                {
                  text: i18n.t('common.fields.customerRegisteredSource.options.onlineIm'),
                  value: '2'
                },
                {
                  text: i18n.t('common.fields.customerRegisteredSource.options.weChatIm'),
                  value: '3'
                }
              ]
            }
          }
        ]
      ).sort((a, b) => a.orderId - b.orderId);
      // 不是企微端就不显示微信昵称和微信Id字段
      if(!this.isWeChat) {
        _fields = _fields.filter(f => f.fieldName != 'weChatNickname' && f.fieldName != 'weChatId')
      }
      return _fields
    },
    // 是否是企微版本
    isWeChat() {
      return getRootWindowInitData()?.tenantType == 2
    },
    // 导出权限
    authExport() {
      return this.initData.loginUser.authorities.CUSTOMER_EXPORT;
    },

    /* 已选择 id列表 */
    selectedIds() {
      return this.multipleSelection.map(item => item.id) || [];
    },

    // 基础版功能是否隐藏产品
    isBasicEditionHideProduct() {
      return isBasicEditionHideProduct()
    },
    isQywx() {
      return getRootWindowInitData().scrm
    },
    customerContactListClassNames() {
      return {
        'customer-contact-list-selected-wechat' : !isEmpty(this.relationWxListValue)
      }
    },
    authorities() {
      return this.initData.loginUser.authorities;
    },
    // 是否有编辑联系人权限
    allowEditLinkman() {
      return this.authorities?.LINKMAN_EDIT
    },
    // 是否有删除联系人权限
    allowDeleteLinkman() {
      return this.authorities?.LINKMAN_DELETE
    },
  },
  filters: {
    displaySelect(value) {
      if (!value) return null;
      if (value && typeof value === 'string') {
        return value;
      }
      if (Array.isArray(value) && value.length) {
        return value.join('，');
      }
      return null;
    },
    formatDate(val) {
      if (!val) return '';
      return formatDate(val, 'YYYY-MM-DD HH:mm:ss');
    }
  },
  mounted() {
    this.auth = (this.initData && this.initData.authorities) || {};

    this.productTemplateConfig = {
      productConfig: (this.initData && this.initData.productConfig) || {
        productType: []
      },
      productFields: (this.initData.productFields || []).sort(
        (a, b) => a.orderId - b.orderId
      )
    };
    this.$eventBus.$on('customer_contact.update_contact_list', this.delaySearch);

    this.paramsSearchRevert();
    this.buildTableColumn();
    this.search();
    let that_ = this;
    // 监听切换后需要重新计算列表高度 后续可以用activated生命周期替换
    window.addEventListener('message', (event)=> {
      const {action, data} = event.data;
      if (action == 'shb.frame.activatedPage'){
        that_.$nextTick(()=> {
          that_.knowTableContainerHeight();
        })
      }
    });
    this.$nextTick(()=> {
      this.knowTableContainerHeight()
      let that_ = this;
      window.onresize = _.debounce(()=>{
        that_.knowTableContainerHeight()
      }, 500)
    })
    // [tab_spec]标准化刷新方式
    window.__exports__refresh = this.search;
  },
  methods: {
    transhForm(data) {
      let str = [];
      if (data && data.length > 0) {
        data.forEach(res => {
          str.push(res.name);
        });
      }
      return str.join(',');
    },
    showAdvancedSetting() {
      window.TDAPP.onEvent('pc：客户联系人-选择列事件');
      // 不是企微端就不显示微信昵称和微信Id字段
      let _columns = this.columns
      if(!this.isWeChat) {
        _columns = _columns.filter(f => f.fieldName != 'weChatNickname' && f.fieldName != 'weChatId')
      }
      this.$refs.advanced.open(_columns);
    },
    buildParams() {
      const sm = Object.assign({}, this.searchModel);
      let params = {
        keyword: sm.keyword,
        pageSize: sm.pageSize,
        pageNum: sm.pageNum
      };

      if (Object.keys(sm.orderDetail || {}).length) {
        params.orderDetail = sm.orderDetail;
      }
      if (Object.keys(sm.moreConditions).length > 0) {
        params = {
          ...params,
          ...sm.moreConditions
        };
      }

      if (this.hasWechat !== null) {
        params.hasWechat = this.hasWechat
      }

      return params;
    },
    // 构建表格固定列
    buildTableFixedColumns() {
      let list = [
        {
          label: i18n.t('common.fields.contact.displayName'),
          displayName: i18n.t('common.fields.contact.displayName'),
          field: 'name',
          fieldName:'name',
          isSystem:true,
          tableName:'customerContact',
          show: true,
          // fixed: true,
          minWidth: '150px'
        },
        {
          label: i18n.t('common.fields.phone.displayName'),
          displayName: i18n.t('common.fields.phone.displayName'),
          field: 'phone',
          fieldName:'phone',
          isSystem:true,
          tableName:'customerContact',
          // fixed: true,
          show: true
        },
        {
          label: i18n.t('common.fields.weChatNickname.displayName'),
          displayName: i18n.t('common.fields.weChatNickname.displayName'),
          fieldName:'weChatNickname',
          field: 'weChatNickname',
          isSystem:true,
          tableName:'customerContact',
          show: this.isWeChat
        },
        {
          label: i18n.t('common.fields.sex.displayName'),
          displayName: i18n.t('common.fields.sex.displayName'),
          fieldName:'sex',
          field: 'sex',
          isSystem:true,
          tableName:'customerContact',
          show: true
        },
        {
          label: i18n.t('common.fields.weChatId.displayName'),
          displayName: i18n.t('common.fields.weChatId.displayName'),
          fieldName:'weChatId',
          field: 'weChatId',
          isSystem:true,
          tableName:'customerContact',
          show: this.isWeChat
        },
        {
          label: i18n.t('common.fields.customer.displayName'),
          displayName: i18n.t('common.fields.customer.displayName'),
          field: 'cusName',
          fieldName:'cusName',
          isSystem:true,
          tableName:'customerContact',
          conType: 'click',
          color: this.getThemeColor,
          needAuth: true,
          click: obj => {
            
            if (!this.hasViewCustomerAuth(obj) || !this.globalIsHaveCustomerViewDetailAuth) return;
            
            let fromId = window.frameElement.getAttribute('id');
            // this.$platform.openTab({
            //   id: `customer_view_${obj.customerId}`,
            //   title: '客户详情',
            //   close: true,
            //   url: `/customer/view/${obj.customerId}?noHistory=1`,
            //   fromId
            // });
            openAccurateTab({
              type: PageRoutesTypeEnum.PageCustomerView,
              key: obj.customerId,
              params: 'noHistory=1',
              fromId
            })
          },
          show: true
        },
        {
          label: i18n.t('common.fields.department.displayName'),
          displayName: i18n.t('common.fields.department.displayName'),
          field: 'dept',
          fieldName:'dept',
          isSystem:true,
          tableName:'customerContact',
          show: true
        },
        {
          label: i18n.t('common.fields.customerRegisteredSource.displayName'),
          displayName: i18n.t('common.fields.customerRegisteredSource.displayName'),
          fieldName:'registeredSource',
          field: 'registeredSource',
          isSystem:true,
          tableName:'customerContact',
          show: true
        },
        {
          label: i18n.t('common.fields.email.displayName'),
          displayName: i18n.t('common.fields.email.displayName'),
          fieldName:'email',
          field: 'email',
          isSystem:true,
          tableName:'customerContact',
          show: false
        },
        {
          label: i18n.t('common.fields.position.displayName'),
          displayName: i18n.t('common.fields.position.displayName'),
          fieldName:'position',
          field: 'position',
          isSystem:true,
          tableName:'customerContact',
          show: false
        },
        {
          label: i18n.t('common.fields.remark.displayName'),
          displayName: i18n.t('common.fields.remark.displayName'),
          field: 'remarks',
          fieldName:'remarks',
          isSystem:true,
          tableName:'customerContact',
          show: false
        },
        {
          label: i18n.t('common.fields.relationProduct.displayName'),
          displayName: i18n.t('common.fields.relationProduct.displayName'),
          field: 'esProductEntities',
          fieldName:'esProductEntities',
          isSystem:true,
          tableName:'customerContact',
          show: false
        },
        {
          label: i18n.t('common.fields.relationAddress.displayName'),
          displayName: i18n.t('common.fields.relationAddress.displayName'),
          fieldName:'addr',
          field: 'addr',
          isSystem:true,
          tableName:'customerContact',
          show: false
        },
        {
          label: i18n.t('common.fields.action.displayName'),
          displayName: i18n.t('common.fields.action.displayName'),
          fieldName:'btnArray',
          field: 'btnArray',
          conType: 'btnArray',
          fixed: 'right',
          isSystem:true,
          tableName:'customerContact',
          btnArr: [
            {
              name: i18n.t('common.base.edit'),
              styleType: obj => {
                return this.allowEditLinkman
                  ? `color: ${this.getThemeColor}`
                  : 'color:#999 !important;cursor: not-allowed;';
              },
              styleType1: obj => {
                return this.allowEditLinkman
                  ? 'color:#595959'
                  : 'color:#BFBFBF !important;cursor: not-allowed;';
              },
              click: obj => {
                if (pending) return;
                if (!this.allowEditLinkman) return;
                this.openDialog(obj);
                this.$track.clickStat(this.$track.formatParams('TO_EDIT', null, 'LIST_OPERATION'))
              }
            },
            {
              name: i18n.t('common.base.delete'),
              styleType: obj => {
                return obj.isMain || !this.allowDeleteLinkman
                  ? 'color:#999 !important;cursor: not-allowed;'
                  : 'color:#FF4D4F !important';
              },
              styleType1: obj => {
                return obj.isMain || !this.allowDeleteLinkman
                  ? 'color:#BFBFBF !important;cursor: not-allowed;'
                  : 'color:#595959';
              },
              click: obj => {
                if (pending) return;
                if (obj.isMain || !this.allowDeleteLinkman) return;
                this.deleteLinkman(obj);
                this.$track.clickStat(this.$track.formatParams('TO_DELETE', null, 'LIST_OPERATION'))
              }
            },
            // 接口404，按豫让要求先去掉该功能
            // {
            //   name: i18n.t('common.base.sync'),
            //   styleType: obj => {
            //     let showBtn = obj.phone == 0 && dingtalk.inDingTalkCrm;
            //     return showBtn ? 'color:#55b7b4;' : 'color:#55b7b4;display: none;';
            //   },
            //   styleType1: obj => {
            //     let showBtn = obj.phone == 0 && dingtalk.inDingTalkCrm;
            //     return !showBtn ? 'color:#595959;' : 'color:#55b7b4;display: none;';
            //   },
            //   click: (obj, idx) => {
            //     if (pending) return;
            //     this.syncDtalkCrmPhone(obj, idx);
            //   }
            // },
          ],
          // 操作列特殊判断 不能用选择列控制它的显示与隐藏 
          show: 'important'
        }
      ]
      
      list = list.filter(field => {
        
        if (field.fieldName === 'email') {
          return this._isShowEmail
        }
        
        return true
        
      })
      
      return list
    },
    // 同步
    async syncDtalkCrmPhone(obj, idx) {
      try {
        let phone = await dingtalk.getCrmData(obj.customerId, obj.id);
        this.$set(this.page.list, idx, {
          ...obj,
          phone
        });
        this.$platform.alert(this.$t('customerContact.syncDtalkCrmPhone.successAlert'));
      } catch (error) {
        console.error(error);
        if(error)this.$platform.alert(error);
      }
      
    },
    async deleteLinkman(lm) {
      if (lm.isMain) return platform.alert(this.$t('customerContact.deleteLinkman.isMainAlert'));
      try {
        const res = await platform.confirm(this.$t('customerContact.deleteLinkman.confirmMsg'));
        if (!res) return;
        pending = true;
        const reqRes = await this.$http.post(
          '/linkman/delete',
          { ids: lm.id },
          false
        );
        pending = false;
        platform.alert(this.$t('customerContact.deleteLinkman.successMsg'));

        this.delaySearch()
        // this.$eventBus.$emit("customer_info_record.update_record_list");
      } catch (e) {
        console.error(e, 'err');
      }
    },
    // 构建表格列
    buildTableColumn() {
      let baseColumns = this.buildTableFixedColumns();
      const localStorageData = this.getLocalStorageData();
      let columnStatus = (localStorageData.columnStatus && localStorageData.columnStatus[this.selectColumnState]) || [];
      let localColumns = columnStatus
        .map((i) => (typeof i == 'string' ? { field: i, show: true } : i))
        .reduce((acc, col, currentIndex) => {
          acc[col.field] = {
            field: col,
            index: currentIndex,
          };
          return acc;
        }, {});
      let columns = [...baseColumns].map(col => {
        let { width, show } = col;
        let localField = (localColumns[col.field] && localColumns[col.field].field) || null;
        let fixLeft = localField?.fixLeft || null;
        if (null != localField) {
          width = typeof localField.width == 'number'
            ? `${localField.width}px`
            : `${localField.width}`.indexOf('px') ? localField.width : '';
          show = localField.show !== false;
        }
        col.show = show;
        col.width = width;
        col.type = 'column';
        col['fixLeft'] = fixLeft && 'left'
        return col;
      });

      if (this.isBasicEditionHideProduct) {
        columns = columns.filter(item => item.field !== 'esProductEntities')
      }
      if (Array.isArray(columnStatus) && columnStatus.length > 0) {
        columns = this.buildSortFields(columns, localColumns);
      }
      this.$set(this, 'columns', columns);
    },
    // 兼容旧版本的 已选择列
    backwardCompatibleColumn() {
      let checkedColumnsOldVersion = storageGet(PRODUCT_CHECK);

      if (!checkedColumnsOldVersion) return;

      let columns = checkedColumnsOldVersion.split(',');
      storageRemove(PRODUCT_CHECK);

      return (columns || [])
        .filter(c => c)
        .map(c => {
          return c;
        });
    },
    /**
     * @description 修改选择列设置
     * @param {Object} event 事件对象
     */
    saveColumnStatus (event) {
      let columns = event.data || [];

      this.columns = [];

      this.$nextTick(() => {
        this.$set(this, 'columns', columns.slice());
        this.saveColumnStatusToStorage();
      });
      this.$message.success(this.$t('common.base.saveSuccess'));
    },
    saveColumnStatusToStorage () {
      const localStorageData = this.getLocalStorageData();
      let columnsStatus = null;

      // 判断是否存储选择列
      const columnsList = this.columns.map((c) => ({
        field: c.field,
        show: c.show,
        width: c.width,
        fixLeft: c.fixLeft
      }));

      if (localStorageData.columnStatus && localStorageData.columnStatus[this.selectColumnState] ) {
        localStorageData.columnStatus[
          `${this.selectColumnState}`
        ] = columnsList;
        columnsStatus = localStorageData.columnStatus;
      } else {
        columnsStatus = {
          [`${this.selectColumnState}`]: columnsList,
        };
      }

      this.saveDataToStorage('columnStatus', columnsStatus);
    },
    // common methods
    getLocalStorageData() {
      const dataStr = storageGet('customerContactListData') || '{}';
      return JSON.parse(dataStr);
    },
    saveDataToStorage(key, value) {
      const data = this.getLocalStorageData();
      data[key] = value;
      storageSet('customerContactListData', JSON.stringify(data));
    },

    // 操作选择
    selectionHandle(selection) {
      let tv = this.selectionCompute(selection);

      let original = this.multipleSelection.filter(ms =>
        this.page.list.some(cs => cs.id === ms.id)
      );

      let unSelected = this.page.list.filter(c =>
        original.every(oc => oc.id !== c.id)
      );

      if (tv.length > this.selectedLimit) {
        this.$nextTick(() => {
          original.length > 0
            ? unSelected.forEach(row => {
              this.$refs.productTemplateTable.toggleRowSelection(row, false);
            })
            : this.$refs.productTemplateTable.clearSelection();
        });
        return this.$platform.alert(this.$t('common.base.tip.choiceLimit', {limit: this.selectedLimit}));
      }

      this.multipleSelection = tv;
      console.log(this.multipleSelection, 'select');

      this.$refs.baseSelectionBar?.openTooltip();
      this.$nextTick(()=>{
        this.knowTableContainerHeight()
      })
    },

    // 计算已选择
    selectionCompute(selection) {
      let tv = [];

      tv = this.multipleSelection.filter(ms =>
        this.page.list.every(c => c.id !== ms.id)
      );
      tv = _.uniqWith([...tv, ...selection], _.isEqual);

      return tv;
    },
    /** 把对象中!!为false的值去除（eg. false, undefined, null...），except 可以把想保留的值留下(eg.[0])
     * 主要用于向后端传参，把无用的空值过滤掉
     * var a = { a: 0, b: 1, c: null, d: undefined, e: false}
     * deleteValueFromObject(a) =>  {b: 1}
     * deleteValueFromObject(a, [0]) =>  {a: 0, b: 1}
     */
    deleteValueFromObject(sourceObj, except = []) {
      let obj = _.cloneDeep(sourceObj);
      if (except.length) {
        Object.keys(obj).forEach(key => {
          if (typeof obj[key] === 'object' && obj[key]) {
            obj[key] = this.deleteValueFromObject(obj[key], except);
          }
          if (!obj[key] && except.every(ex => ex !== obj[key])) {
            delete obj[key];
          }
        });
      } else {
        Object.keys(obj).forEach(key => {
          if (typeof obj[key] === 'object' && obj[key]) {
            obj[key] = this.deleteValueFromObject(obj[key]);
          }
          if (!obj[key]) {
            delete obj[key];
          }
        });
      }
      if (Object.keys(obj).length) {
        return obj;
      }
      return undefined;
    },
    // 跳转 至客户详情
    goCustomerInfo(id) {
      let fromId = window.frameElement.getAttribute('id');

      // this.$platform.openTab({
      //   id: `customer_view_${id}`,
      //   title: '客户详情',
      //   close: true,
      //   url: `/customer/view/${id}?noHistory=1`,
      //   fromId
      // });
      openAccurateTab({
        type: PageRoutesTypeEnum.PageCustomerView,
        key: id,
        params: 'noHistory=1',
        fromId
      })
    },
    // 页码数切换
    handleSizeChange(pageSize) {
      this.searchModel.pageSize = pageSize;
      this.searchModel.pageNum = 1;

      this.localStorageSet('pageSize', pageSize, PRODUCT_TEMPLATE_LIST_DATA);
      this.search();
    },
    // 跳转
    jump(pageNum) {
      this.searchModel.pageNum = pageNum;
      this.search();
    },
    /* 获取本地数据 */
    localStorageGet(key) {
      try {
        const dataStr = storageGet(key) || '{}';
        return JSON.parse(dataStr);
      } catch (error) {
        console.log('error: ', error);
        return {};
      }
    },
    /* 设置本地数据 */
    localStorageSet(key, value, rootKey = null) {
      try {
        if (!rootKey) {
          storageSet(key, JSON.stringify(value));
        } else {
          const data = this.localStorageGet(rootKey);

          data[key] = value;
          storageSet(rootKey, JSON.stringify(data));
        }
      } catch (err) {
        console.log('localStorageSet err', err);
      }
    },
    // 搜索
    search() {
      const params = this.buildParams();
      this.loadingListData = true;
      return getContactList(params)
        .then(res => {
          res = res.result;
          if (!res || !res.list) {
            this.page = new Page();
          } else {
            this.page.merge(res);

            this.page.list = res.list.map(l => {
              l['customer'] = { id: l.customerId };
              l['remark'] = l.remarks || '';
              l['department'] = l.dept || '';
              l['productId'] = l.esProductEntities || [];
              let attribute = l.attribute ? l.attribute : {};

              let list = {
                ...l,
                ...attribute
              };
              return list;
            });
          }

          return res;
        })
        .then(() => {
          this.$refs.productTemplateListPage.scrollTop = 0;
          this.matchSelected(); // 把选中的匹配出来
          this.loadingListData = false;
        })
        .catch(err => {
          this.loadingListData = false;
          console.error('err', err);
        });
    },
    // 设置高级搜索面板 列
    setAdvanceSearchColumn(command) {
      this.columnNum = Number(command);
      try {
        storageSet(
          PRODUCT_TEMPLATE_LIST_ADVANCE_SEARCH_COLUMN_NUMBER,
          this.columnNum
        );
      } catch (error) {
        console.log(error);
      }
    },
    sortChange(option) {
      /**
       * 目前情况：
       * 所有字段理应后台获取，但是获取的所有字段中没有 createTime
       *
       */
      try {
        const { prop, order } = option;
        if (!order) {
          this.searchModel.orderDetail = {};
          return this.search();
        }

        let sortModel = {
          isSystem:
            prop === 'createTime' || prop === 'updateTime' || prop === 'type'
              ? 1
              : 0,
          sequence: order === 'ascending' ? 'ASC' : 'DESC',
          column:
            prop === 'createTime' || prop === 'updateTime' || prop === 'type'
              ? `productTemplate.${prop}`
              : prop
        };

        const sortedField = this.productTemplateConfig.productFields.filter(
          sf => sf.fieldName === prop
        )[0] || {};

        if (
          prop === 'createTime'
          || prop === 'updateTime'
          || sortedField.formType === 'date'
          || sortedField.formType === 'datetime'
        ) {
          sortModel.type = 'date';
        } else {
          sortModel.type = sortedField.formType;
        }

        this.searchModel.orderDetail = sortModel;

        this.search();
      } catch (e) {
        console.error('product template sortChange err', e);
      }
    },
    // 搜索参数恢复
    paramsSearchRevert() {
      const localStorageData = this.localStorageGet(PRODUCT_TEMPLATE_LIST_DATA);

      if (localStorageData && localStorageData.pageSize) {
        this.searchModel.pageSize = Number(localStorageData.pageSize);
      }

      const num = storageGet(
        PRODUCT_TEMPLATE_LIST_ADVANCE_SEARCH_COLUMN_NUMBER
      ) || 1;
      this.columnNum = Number(num);
    },
    panelSearchAdvancedToggle() {
      window.TDAPP.onEvent('pc：产品模板-高级搜索事件');
      this.$refs.searchPanel.open();

      this.$nextTick(() => {
        let forms = document.getElementsByClassName('advanced-search-form');
        for (let i = 0; i < forms.length; i++) {
          let form = forms[i];
          form.setAttribute('novalidate', true);
        }
      });
    },
    /**
     * @description 全量搜索
     */
    powerfulSearch() {
      this.searchModel.pageNum = 1;
      this.searchModel.moreConditions = this.$refs.searchPanel.buildParams();

      this.trackEventHandler('search');
			this.$track.clickStat(this.$track.formatParams('ADVANCED_SEARCH'));
      this.search();
    },
    resetParams() {
      window.TDAPP.onEvent('pc：产品模板-重置事件');
      this.searchIncludeMoreConditions = false;
      this.searchModel = {
        keyword: '',
        pageNum: 1,
        pageSize: this.page.pageSize,
        orderDetail: {},
        moreConditions: {}
      };

      this.$refs.searchPanel.resetParams();
      this.search();
    },
    // TalkingData事件埋点
    trackEventHandler(type) {
      if (type === 'search') {
        window.TDAPP.onEvent('pc：产品模板-搜索事件');
        return;
      }
      if (type === 'moreAction') {
        window.TDAPP.onEvent('pc：产品管理-更多操作事件');
        return;
      }
    },
    openOutsideLink(e) {
      let url = e.target.getAttribute('url');
      if (!url) return;
      if (!/http/gi.test(url))
        return this.$platform.alert(this.$t('customerContact.openOutsideLink.urlFailAlert'));
      this.$platform.openLink(url);
    },
    buildTextarea(value) {
      return value
        ? value.replace(link_reg, match => {
          return `<a href="javascript:;" target="_blank" url="${match}">${match}</a>`;
        })
        : '';
    },
    getRowKey(row) {
      return row.id;
    },
    openDialog(contact) {
      // 弹窗参考数据
      // TO DO 权限
      this.selectedContact = contact;
      this.$nextTick(this.$refs.EditContactDialog.openDialog);
    },
    /**
     * 是否有操作联系人权限，需要满足以下条件之一：
     *
     * 1. 编辑客户全部权限： 全部客户
     * 2. 编辑客户团队权限： 没有团队的客户都可编辑，有团队的按团队匹配。 包含个人权限
     * 3. 编辑客户个人权限： 自己创建的 或 客户负责人 或 客户协同人
     */
    hasEditCustomerAuth(customer) {
      let loginUserId = this.initData.loginUser.userId;
      return AuthUtil.hasAuthWithDataLevel(
        this.permission(),
        'CUSTOMER_EDIT',
        // 团队权限判断
        () => {
          let tags = Array.isArray(customer.tags) ? customer.tags : [];
          // 无团队则任何人都可编辑
          if (tags.length == 0) return true;

          let loginUserTagIds = this.initData.loginUser.tagIdsWithChildTag || [];
          return tags.some(tag => loginUserTagIds.indexOf(tag.id) >= 0);
        },
        // 个人权限判断
        () => {
          return (
            customer.createUser == loginUserId
            || this.isCustomerManagerOrSynergies(customer)
          );
        }
      );
    },
    /**
     * 当前用户是否是该客户负责人
     * 客户负责人用于和客户创建人相同权限
     */
    isCustomerManager(customer) {
      return this.initData.loginUser.userId === customer.customerManager;
    },
    /**
     * 当前用户是否是该客户协同人
     */
    isCustomerSynergies(customer) {
      let customerSynergies = customer.synergies || []
      return !!customerSynergies.find(v => v.userId === this.initData.loginUser.userId)
    },

    /**
     * 当前用户是否是该客户负责人或协同人
     */
    isCustomerManagerOrSynergies(customer) {
      return this.isCustomerManager(customer) || this.isCustomerSynergies(customer)
    },
    /**
     * 是否有查看客户权限，需要满足以下条件之一：
     *
     * 1. 查看客户全部权限： 全部客户
     * 2. 查看客户团队权限： 没有团队的客户都可查看，有团队的按团队匹配。 包含个人权限
     * 3. 查看客户个人权限： 自己创建的 或 客户负责人 或 客户协同人
     */
    hasViewCustomerAuth(customer) {
      let loginUserId = this.initData.loginUser.userId;
      return AuthUtil.hasAuthWithDataLevel(
        this.permission(),
        'CUSTOMER_VIEW',
        // 团队权限判断
        () => {
          let tags = Array.isArray(customer.tags) ? customer.tags : [];
          // 无团队则任何人都可编辑
          if (tags.length == 0) return true;

          let loginUserTagIds = this.initData.loginUser.tagIdsWithChildTag || [];
          return tags.some(tag => loginUserTagIds.indexOf(tag.id) >= 0);
        },
        // 个人权限判断
        () => {
          return (
            customer.createUser == loginUserId
            || this.isCustomerManagerOrSynergies(customer)
          );
        }
      );
    },
    /** 当前用户的权限 */
    permission() {
      return this.initData.loginUser.authorities;
    },

    toggleSelection(rows) {
      let isNotOnCurrentPage = false;
      let item = undefined;
      let row = undefined;

      if (rows) {
        for (let i = 0; i < rows.length; i++) {
          row = rows[i];
          isNotOnCurrentPage = this.page.list.every(item => {
            return item.id !== row.id;
          });
          if (isNotOnCurrentPage) return;
        }
        rows.forEach(row => {
          this.$refs.productTemplateTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.productTemplateTable.clearSelection();
        this.multipleSelection = [];
      }
    },

    // 切换已选择
    selectionToggle(rows) {
      let isNotOnCurrentPage = false;
      let item = undefined;
      let row = undefined;

      if (rows) {
        for (let i = 0; i < rows.length; i++) {
          row = rows[i];
          isNotOnCurrentPage = this.page.list.every(item => {
            return item.id !== row.id;
          });
          if (isNotOnCurrentPage) return;
        }
        rows.forEach(row => {
          this.$refs.productTemplateTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.productTemplateTable.clearSelection();
        this.multipleSelection = [];
      }
    },
    /**
     * 导出产品
     * @param {Boolean} exportAll -- 是否导出全部
     */
    exportProduct(exportAll = false) {
      let ids = [];
      let fileName = `${formatDate(
        safeNewDate(),
        this.$t('customerContact.exportProduct.fileName', {date: 'YYYY-MM-DD'})
      )}`;

      if (!exportAll) {
        if (!this.multipleSelection.length)
          return this.$platform.alert(this.$t('common.base.tip.exportNoChoice'));
        ids = this.selectedIds;
      }
      console.log(ids, 'export');
      this.$refs.exportProductTemplatePanel.open(ids, fileName);
    },
    // 导出 列
    exportColumns() {
      // 导出暂时先隐藏微信昵称和微信ID
      const columns = this.columns.filter(item=>item.field != 'weChatId' && item.field != 'weChatNickname')
      return columns.map(c => {
        if (
          c.field !== 'customerAddress'
          && c.field !== 'remindCount'
          && c.field !== 'updateTime'
          && c.field !== 'btnArray'
        ) {
          c.export = true;
        }

        return c;
      });
    },
    // 构建产品导出参数
    exportParamsBuild(checkedArr, ids) {
      let exportAll = !ids || ids.length == 0;
      let exportSearchModel = exportAll
        ? {
          ...this.buildParams(),
          exportTotal: this.page.total
        }
        : { exportTotal: ids.length };

      let newCheckedArr = JSON.parse(JSON.stringify(checkedArr));
      if (newCheckedArr.indexOf('registeredSource') > -1) {
        newCheckedArr[newCheckedArr.indexOf('registeredSource')] = 'weChatFansExportEntities';
      }
      if (newCheckedArr.indexOf('esProductEntities') > -1) {
        newCheckedArr[newCheckedArr.indexOf('esProductEntities')] = 'products';
      }
      return {
        linkmanChecked: newCheckedArr.join(','),
        data: exportAll ? '' : ids.join(','),
        exportSearchModel: JSON.stringify(exportSearchModel)
      };
    },
    // 检测导出条数
    exportCountCheck(ids, max) {
      let exportAll = !ids || ids.length == 0;

      return exportAll && this.multipleSelection.length > max
        ? this.$t('common.base.tip.exportLimit', { max })
        : null;
    },

    // 取消选择的产品
    selectProductTemplateCancel(productItem) {
      if (!productItem || !productItem.id) return;

      this.multipleSelection = this.multipleSelection.filter(
        ms => ms.id !== productItem.id
      );
      this.multipleSelection.length < 1
        ? this.selectionToggle()
        : this.selectionToggle([productItem]);
    },

    // match data
    matchSelected() {
      if (!this.multipleSelection.length) return;
      const selected = this.page.list.filter(c => {
        if (this.multipleSelection.some(sc => sc.id === c.id)) {
          this.multipleSelection = this.multipleSelection.filter(
            sc => sc.id !== c.id
          );
          this.multipleSelection.push(c);
          return c;
        }
      }) || [];

      this.$nextTick(() => {
        this.toggleSelection(selected);
      });
    },
    onCustonerRelationWxStatusChangedHandler(value) {
      let hasWechat = null
      
      if (value.length == 1) {
        hasWechat = value[0]
      }
      
      this.relationWxListValue = value
      this.hasWechat = hasWechat
      this.search()
    },
    /**
     * @des 表单拖拽钩子函数
     */
    headerDragend (newWidth, oldWidth, column, event) {
      let data = this.columns
        .map((item) => {
          if (item.fieldName === column.property) {
            item.width = column.width;
          }
          return item;
        })
        .map((item) => {
          return {
            field: item.field,
            show: item.show,
            width: item.width,
          };
        });
      this.modifyColumnStatus({ type: 'column', data });
    },
    /**
     * @description 修改选择列设置
     * @param {Object} event 事件对象
     */
    modifyColumnStatus (event) {
      let columns = event.data || [],
        colMap = columns.reduce(
          (acc, col) => (acc[col.field] = col) && acc,
          {}
        );
      this.columns.forEach((col) => {
        let newCol = colMap[col.field];
        if (null != newCol) {
          this.$set(col, 'show', newCol.show);
          this.$set(col, 'width', newCol.width);
        }
      });

      this.saveColumnStatusToStorage();
    },
    buildSortFields(originFields = [], fieldsMap = {}) {
      let fields = [];
      let unsortedFields = [];

      originFields.forEach((originField) => {
        let { fieldName } = originField;
        let field = fieldsMap[fieldName];

        if (field) {
          let { index } = field;
          fields[index] = originField;
        } else {
          unsortedFields.push(originField);
        }
      });

      return fields.concat(unsortedFields);
    },
    /**
     * @des 获取列表当前的可滚动高度
     */
		 knowTableContainerHeight(){
      let min = 440;
      try {
        let window_ = window.innerHeight;
        let header = this.$refs.tableHeaderContainer?.offsetHeight || 0;
        let do_ = this.$refs.tableDoContainer?.offsetHeight || 0;
        let footer = this.$refs.tableFooterContainer?.offsetHeight || 0;
        let selection = this.$refs.BaseSelectionBarComponent?.offsetHeight || 0;
        min = window_ - header * 1 - do_ * 1 - footer * 1 - selection * 1  - 24 - 12;
        console.log(window_, header, do_, footer, selection, 'window_, header, do_, footer, selection');
        console.log(min, 'min')
        min = min > 440 ? min : 440;
      } catch (error) {
        console.warn(error, 'error try catch');
      }
      this.$set(this, 'tableContainerHeight', `${min}px`)
    },
    changePackUp(){
      this.packUp = !this.packUp;
      this.$nextTick(()=>{
        this.knowTableContainerHeight()
      })
    },
    delaySearch() {
      setTimeout(() => {
        this.search()
      }, 1000);
    },
  },
  components: {
    [SearchPanel.name]: SearchPanel,
    [EditContactDialog.name]: EditContactDialog
  }
};
</script>

<style lang="scss">

html,
body {
  height: 100%;
}

.mar-l-10 {
  margin-left: 10px;
}
.color-green {
  color: $color-primary-light-6;
}
.font-16 {
  font-size: 16px;
}

.product-template-list-view {
  height: 100%;
  padding: 10px;
  .el-table {
    border-top: none;
  }
  .panel-title {
    border-bottom: 1px solid rgb(242, 248, 247);
    color: rgb(132, 138, 147);

    font-size: 16px;
    font-weight: normal;
    line-height: 60px;

    display: flex;
    justify-content: space-between;

    padding: 0 25px;

    .iconfont:hover {
      cursor: pointer;
    }
  }
}

// search
.product-template-list-search-group {
  .advanced-search-function,
  .base-search {
    background: #fff;
    border-radius: 4px;
  }

  .base-search {
    font-size: 14px;

    display: flex;
    justify-content: flex-end;
    align-items: center;

    padding: 16px;

    .product-template-list-base-search-group {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .el-input {
        width: 400px;
        input {
          border-radius: 4px 0 0 4px
        }
      }

      a {
        line-height: 33px;
      }
    }

    .advanced-search-visible-btn {
      background: #fff;
      border-color: $color-primary;
      @include fontColor();
      font-size: 14px;
      height: 32px;
      line-height: 32px;
      padding: 0 13px;
      white-space: nowrap;

      &:hover {
        cursor: pointer;
      }
    }
  }
}

.advanced-search-form {
  .two-columns {
    display: flex;
    flex-wrap: wrap;
    .el-form-item {
      width: 50%;
    }
  }

  .el-form-item {
    .el-form-item__content,
    .el-select,
    .base-dist-picker,
    .el-cascader,
    .el-date-editor {
      width: 290px !important;
    }
  }

  .advanced-search-btn-group {
    background: #fff;

    display: flex;
    justify-content: flex-end;

    width: 100%;
    padding: 15px 20px;

    position: absolute;
    bottom: 0px;

    .base-button {
      margin: 0 10px;
    }
  }
}

.advanced-search-function {
  margin-top: 10px;
  padding-bottom: 10px;

  h4 {
    border-bottom: 1px solid #f4f4f4;
    padding: 10px;
  }

  .el-row {
    padding: 5px 0;
  }
  .input-label {
    text-align: right;
    line-height: 32px;
    padding-right: 0;
  }
}

// list
.product-template-list-content {
  margin-top: 10px;

  .product-template-table {
    padding: 16px;
    border: 0;

    &:before {
      height: 0;
    }

    .product-template-table-header th {
      background: #f5f5f5;
      color: $text-color-primary;
      font-weight: normal;
    }

    th {
      color: #333;
      font-size: 14px;
    }
    td {
      color: #666;
      font-size: 13px;
    }

    .view-detail-btn {
      @include fontColor();
    }
    
    .view-detail-btn-disabled {
      color: #666 !important;
      cursor: default;
    }

    .select-column .el-checkbox {
      position: relative;
      top: 3px;
    }
  }

  .table-footer {
    background: #fff;
    border-radius: 0 0 4px 4px;

    display: flex;
    justify-content: space-between;

    padding: 0px 10px 10px 10px;

    .list-info {
      color: #767e89;

      font-size: 13px;
      line-height: 32px;

      margin: 0;

      .iconfont {
        position: relative;
        top: 1px;
      }
    }

    .el-pagination__jump {
      margin-left: 0;
    }
  }

  .superscript {
    .customer-contact-name {
      padding-left: 20px;
    }
  }
}

.product-template-panel-btn {
  float: right;
  cursor: pointer;
  font-size: 14px;
  margin-right: 5px;

  &:hover {
    @include fontColor();
  }
}

// product-template selected panel
.product-template-selected-count {
  cursor: pointer;
  @include fontColor();

  font-size: 13px;

  padding: 0 3px;
  width: 15px;

  text-align: center;
}

.product-template-selected-panel {
  font-size: 14px;
  height: calc(100% - 51px);
}

.product-template-selected-tip {
  padding-top: 80px;

  img {
    display: block;
    width: 160px;
    margin: 0 auto;
  }

  p {
    color: $text-color-regular;

    line-height: 20px;
    text-align: center;

    margin: 8px 0 0 0;
  }
}

.product-template-selected-list {
  height: 100%;
  padding: 10px;
  overflow-y: auto;
}

.product-template-selected-row {
  border-bottom: 1px solid #ebeef5;

  display: flex;
  flex-flow: row nowrap;

  font-size: 13px;
  line-height: 36px;

  &:hover {
    background-color: #f5f7fa;

    .product-template-selected-delete {
      visibility: visible;
    }
  }
}

.product-template-selected-head {
  background-color: #f0f5f5;
  color: #333;
  font-size: 14px;
}

.product-template-selected-sn {
  padding-left: 10px;
  flex: 1;
  @include text-ellipsis;
}

.product-template-selected-name {
  padding-left: 10px;
  width: 150px;
  @include text-ellipsis;
}

.product-template-selected-delete {
  width: 36px;
}

.product-template-selected-row button.product-template-selected-delete {
  background-color: transparent;
  color: #646b78;

  border: none;

  padding: 0;
  width: 36px;
  height: 36px;

  outline: none;
  visibility: hidden;

  i {
    font-size: 14px;
  }

  &:hover {
    color: #e84040;
  }
}

// operation
.product-template-columns-dropdown-menu {
  max-height: 300px;
  overflow: auto;
  .el-dropdown-menu__item {
    padding: 0;
  }
  .el-checkbox {
    width: 100%;
    padding: 5px 15px;
    margin: 0;
  }
}

.operation-bar-container {
  background: #fff;
  border-radius: 4px 4px 0 0;

  display: flex;
  justify-content: space-between;

  padding: 16px 16px 0;

  .el-dropdown-btn {
    display: inline-block;
    // line-height: 32px;
    outline: none;
    .iconfont {
      margin-left: 5px;
    }
    
    &:hover {
      background-color: transparent;
      cursor: pointer;
      @include fontColor();
    }
  }
}

.customer-contact-name {
  display: flex;
}
</style>

<style lang="scss" scoped>
::v-deep .el-table__row{
  td:not(.is-hidden):last-child{
    border-left:1px solid #EBEEF5;
  }

}
::v-deep .el-table__header{
  th:not(.is-hidden):last-child{
    border-left:1px solid #EBEEF5;
  }
}
.customer-contact-list-view {
  .action-button-group {
    display: flex;
  }
}
.customer-contact-list-selected-wechat {
  .biz-customer-tag-select {
    .el-dropdown-link {
      color: $color-primary;
    }
  }
}
.lang-select-dropdown {
  margin-top: 0!important;
}
.cur-point {
  color: $color-primary-light-6;
}
::v-deep .el-dropdown-menu__item:not(.is-disabled):hover {
  div {
    color: $color-primary-light-6!important;
  }
}
</style>
